package com.example.springredirectafterlogin.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/custom")
@Slf4j
public class LoginController {
    @Resource(name = "authenticationManager")
    private AuthenticationManager authenticationManager;

    @PostMapping(value = "/login")
    public void login(@RequestParam("username") final String username, @RequestParam("password") final String password, final HttpServletRequest request){
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,password);
        log.info("username={},password={}",username,password);
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        HttpSession session = request.getSession(true);
        session.setAttribute("SPRING_SECURITY_CONTEXT",securityContext);
    }

    @GetMapping(value = "/login.html")
    public String loginIndex(){
        return "login";
    }

    @RequestMapping(value = "/print",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<SecurityContext> printUser(){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return new ResponseEntity<>(securityContext, HttpStatus.OK);
    }
}
